package com.capgemini.diabeo;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.*;
import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation;

import com.capgemini.diabeo.dummy.DummyContent;
import com.capgemini.diabeo.settings.SettingsActivity;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DishDisplay extends Activity {

	public static final String PREFS_NAME = "PrefsDishes";
	private int id_repas = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {



		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dish_display);
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		Map<String, ?> allDishes = settings.getAll();
		ArrayList<HashMap<String,String>> dishList = new ArrayList<HashMap<String,String>>();
		ListView lv = (ListView)findViewById(R.id.dishesList);
		float totalGlucides = 0;
		float totalIG = 0;
		float totalLipides = 0;
		float dose = 0;
		ArrayList<Double> distribution = new ArrayList<Double>();
		ArrayList<String> dishesNames = new ArrayList<String>();
		TextView tvGlucides = (TextView)findViewById(R.id.tvTotalGlucides);
		TextView tvIG = (TextView)findViewById(R.id.tvTotalIG);
		TextView tvLipides = (TextView)findViewById(R.id.tvTotalLipides);
		TextView tvDose = (TextView)findViewById(R.id.tvDose);
		for(Map.Entry<String, ?> entry : allDishes.entrySet())
		{
			Cursor c = readDishes(entry.getValue().toString());

			if (c.moveToFirst()) {
				do {
					String nom = c.getString(c.getColumnIndex(AlimentsEntry.COLUMN_NAME_NOM));
					String id = c.getString(c.getColumnIndex(AlimentsEntry.COLUMN_NAME_ALIMENT_ID));
					String quantite = c.getString(c.getColumnIndex(AlimentsEntry.COLUMN_NAME_QUANTITE));
					String glucide = c.getString(c.getColumnIndex(AlimentsEntry.COLUMN_NAME_GLUCIDE));
					String lipide = c.getString(c.getColumnIndex(AlimentsEntry.COLUMN_NAME_LIPIDE));
					String ig = c.getString(c.getColumnIndex(AlimentsEntry.COLUMN_NAME_IG));


					HashMap<String, String> dish = new HashMap<String, String>();
					dish.put(AlimentsEntry.COLUMN_NAME_NOM, nom);
					dish.put(AlimentsEntry.COLUMN_NAME_ALIMENT_ID, id);
					dish.put(AlimentsEntry.COLUMN_NAME_QUANTITE, quantite);
					dish.put(AlimentsEntry.COLUMN_NAME_GLUCIDE, glucide);
					dish.put(AlimentsEntry.COLUMN_NAME_LIPIDE, lipide);
					dish.put(AlimentsEntry.COLUMN_NAME_IG, ig);

					
					totalGlucides = totalGlucides + Float.parseFloat(glucide);
					totalIG = totalIG + Float.parseFloat(ig);
					totalLipides = totalLipides + Float.parseFloat(lipide);

					//Remplissage pour le diagramme camembert
					distribution.add(Double.parseDouble(glucide));
					dishesNames.add(nom);
					
					dishList.add(dish);
					//Insertion des ID des plats en BDD
					insertMealHistorique(Integer.parseInt(id), id_repas);

				} while (c.moveToNext());
			}
		}
		//Suppression de toutes les ID du fichier de préf�rence
		editor.clear();
		editor.commit();

		id_repas++; // Inutile, prend toujours la valeur 1;

		/**** Calcul de la dose d'insuline correspondante **/
		String mealChoice = MealChoice.mealChoice;
		HashMap<String, String> repereCalcul = retrieveSettings(mealChoice);
		String rapportRepas = repereCalcul.get(mealChoice);
		//Version BDD : On fait par rapport au tableau stoqu� en BDD
		/*int totalGlucidesToInt = Math.round(totalGlucides);
		String totalGlucidesToString = Integer.toString(totalGlucidesToInt);
		Cursor calcul = readInsuline(totalGlucidesToString, rapportRepasMatin);
		if (calcul.moveToFirst()) {
			do {
				//Methode de calcul utilisée. Retourne un float et non un String
				//dose = calcul.getString(calcul.getColumnIndex(AlimentsEntry.COLUMN_NAME_DOSE));	
			} while (calcul.moveToNext());
		}*/

		/**Version Calcul : On fait par rapport au calcul (glucide x rapport) / 10 **/
		Float rapportRepasMatinToFloat = Float.parseFloat(rapportRepas);
		dose = (totalGlucides * rapportRepasMatinToFloat)/10;
		tvGlucides.setText("Total Glucides : "+totalGlucides + " g");
		tvIG.setText("Total IG : "+totalIG);
		tvLipides.setText("Total Lipides : "+totalLipides + " g");
		tvDose.setText("Vous avez besoin d'une dose d'insuline de : "+dose + " g");

		/** Librarie AChartEngine **/
		final LinearLayout rl=(LinearLayout)findViewById(R.id.layoutGraph);

		final GraphicalView gvBar = createIntent(totalGlucides);
		final GraphicalView gvPie = openPieChart(distribution, dishesNames);
		
		gvPie.setOnClickListener(new View.OnClickListener() {
		    @Override
		    public void onClick(View v) {
		      SeriesSelection seriesSelection = gvPie.getCurrentSeriesAndPoint();
		      if (seriesSelection != null) {
		       Toast.makeText(DishDisplay.this, seriesSelection.getValue() + "g de Glucides",
		            Toast.LENGTH_SHORT).show();
		      }
		    }
		  });
	
		/**Cr�ation de la listview puis calcul de sa hauteur **/
		MealAdapter adapter = new MealAdapter(this, dishList);
		lv.setAdapter(adapter);
		Helper.getListViewSize(lv);
		//Initialisation : affichage du diagramme en camembert
		rl.addView(gvPie);
		
		Button btn_pieChart = (Button)findViewById(R.id.btn_pie_chart);
		btn_pieChart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				rl.removeAllViews();
				rl.addView(gvPie);
			}
		});

		Button btn_barChart = (Button)findViewById(R.id.btn_bar_chart);
		btn_barChart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				rl.removeAllViews();
				rl.addView(gvBar);
			}
		});

	}


	public static Cursor readDishes(String id)
	{ 
		SQLiteDatabase dbread = DummyContent.dbOpenHelper.getReadableDatabase();
		String[] projection = {
				AlimentsEntry.COLUMN_NAME_NOM,
				AlimentsEntry.COLUMN_NAME_ALIMENT_ID,
				AlimentsEntry.COLUMN_NAME_QUANTITE,
				AlimentsEntry.COLUMN_NAME_GLUCIDE,
				AlimentsEntry.COLUMN_NAME_LIPIDE,
				AlimentsEntry.COLUMN_NAME_IG};
		/*  String sortOrder = AlimentsEntry.COLUMN_NAME_ALIMENT_ID + " DESC";*/

		Cursor c = dbread.query(
				AlimentsEntry.TABLE_NAME,
				projection,
				AlimentsEntry.COLUMN_NAME_ALIMENT_ID + " like " + "\"" + id + "\"" ,
				null,
				AlimentsEntry.COLUMN_NAME_NOM,
				null,
				null
				);
		return c;    
	}

	public void insertMealHistorique(int id_plat, int id_repas)
	{
		SQLiteDatabase dbread = DummyContent.dbOpenHelper.getReadableDatabase();
		ContentValues values = new ContentValues();
		values.put(AlimentsEntry.COLUMN_NAME_PLAT_ID, id_plat); // inserting a string
		values.put(AlimentsEntry.COLUMN_NAME_REPAS_ID, id_repas); // inserting an int

		// Inserting Row
		dbread.insert(AlimentsEntry.TABLE_NAME_HISTORIQUE, null, values);
	}

	public static Cursor readInsuline(String glucide ,String id)
	{ 
		SQLiteDatabase dbread = DummyContent.dbOpenHelper.getReadableDatabase();
		String[] projection = {AlimentsEntry.COLUMN_NAME_DOSE};
		/*  String sortOrder = AlimentsEntry.COLUMN_NAME_ALIMENT_ID + " DESC";*/

		Cursor c = dbread.query(
				AlimentsEntry.TABLE_NAME_CALCUL,
				projection,
				AlimentsEntry.COLUMN_NAME_RATIO + " like " + "\"" + id + "\" AND " +
						AlimentsEntry.COLUMN_NAME_GLUCIDES_REPAS + " like " + "\"" + glucide + "\"",
						null,
						null,
						null,
						null
				);
		return c;    
	}


	public HashMap<String, String> retrieveSettings(String mealChoice)
	{
		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		String rapport = sharedPrefs.getString(mealChoice, null);
		HashMap<String, String> reperesRepas = new HashMap<String, String>();
		reperesRepas.put(mealChoice, rapport);
		return reperesRepas;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.dish_display, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_settings:
			Intent i2 = new Intent(this, SettingsActivity.class);
			startActivity(i2);
			break;
		default:
			break;
		}

		return true;
	} 

	@Override
	public void onBackPressed() {
		Intent i = new Intent(this, AddDishListActivity.class);
		startActivity(i);
		return;
	}

	/*** Librarie AChartengine ***/
	public GraphicalView createIntent(float totalGlucides) {
		String[] titles = new String[] { "Glucides (g)"};
		List<double[]> values = new ArrayList<double[]>();

		//	values.add(new double[] { totalGlucides, totalIg, totalLipides,10230, 11300, 10040,14230, 12300, 14240, 11300, 10040,14240});
		values.add(new double[] { totalGlucides});

		int[] colors = new int[] { Color.parseColor("#77c4d3")};
		XYMultipleSeriesRenderer renderer = buildBarRenderer(colors);
		renderer.setOrientation(Orientation.HORIZONTAL);
		setChartSettings(renderer, "Glucides des repas", "Temps", "Glucides (g)", 0.5,
				2, 0, 100, Color.BLACK, Color.BLACK);
		renderer.setXLabels(1);
		renderer.setYLabels(10);
		renderer.addXTextLabel(1, "Matin 25/03");
		renderer.addXTextLabel(2, "Midi 25/03");
		int length = renderer.getSeriesRendererCount();
		for (int i = 0; i < length; i++) {
			SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i);
			seriesRenderer.setDisplayChartValues(true);
		}


		final GraphicalView grfv = ChartFactory.getBarChartView(DishDisplay.this, buildBarDataset(titles, values), renderer,Type.DEFAULT);

		return grfv;
	}
	protected XYMultipleSeriesRenderer buildBarRenderer(int[] colors) {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		renderer.setAxisTitleTextSize(16);
		renderer.setChartTitleTextSize(20);
		renderer.setLabelsTextSize(15);
		renderer.setLegendTextSize(15);
		renderer.setBarSpacing(0.5f);

		renderer.setMarginsColor(Color.parseColor("#EEEDED"));
		renderer.setXLabelsColor(Color.BLACK);
		renderer.setYLabelsColor(0,Color.BLACK);

		renderer.setApplyBackgroundColor(true);
		renderer.setBackgroundColor(Color.parseColor("#FBFBFC"));

		int length = colors.length;
		for (int i = 0; i < length; i++) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(colors[i]);
			r.setChartValuesSpacing(15);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}
	protected XYMultipleSeriesDataset buildBarDataset(String[] titles, List<double[]> values) {
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		int length = titles.length;
		for (int i = 0; i < length; i++) {
			CategorySeries series = new CategorySeries(titles[i]);
			double[] v = values.get(i);
			int seriesLength = v.length;
			for (int k = 0; k < seriesLength; k++) {
				series.add(v[k]);
			}
			dataset.addSeries(series.toXYSeries());
		}
		return dataset;
	}
	protected void setChartSettings(XYMultipleSeriesRenderer renderer, String title, String xTitle,
			String yTitle, double xMin, double xMax, double yMin, double yMax, int axesColor,
			int labelsColor) {
		renderer.setChartTitle(title);
		renderer.setYLabelsAlign(Align.RIGHT);
		renderer.setXTitle(xTitle);
		renderer.setYTitle(yTitle);
		renderer.setXAxisMin(xMin);
		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);
		renderer.setMargins(new int[] { 10, 65, 10, 15 });
		renderer.setAxesColor(axesColor);
		renderer.setLabelsColor(labelsColor);
	}

	/***Pie Chart 
	 * @return **/
	private GraphicalView openPieChart(ArrayList<Double> distribution, ArrayList<String> code){

		// Color of each Pie Chart Sections
		int[] colors = { Color.BLUE, Color.MAGENTA, Color.GREEN, Color.CYAN, Color.RED,
				Color.YELLOW };

		// Instantiating CategorySeries to plot Pie Chart
		CategorySeries distributionSeries = new CategorySeries(" Gramme de Glucide par plat dans un repas");
		for(int i=0 ;i < distribution.size();i++){
			// Adding a slice with its values and name to the Pie Chart
			distributionSeries.add(code.get(i), distribution.get(i));
		}

		// Instantiating a renderer for the Pie Chart
		DefaultRenderer defaultRenderer  = new DefaultRenderer();
		for(int i = 0 ;i<distribution.size();i++){
			SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
			seriesRenderer.setColor(colors[i]);
			seriesRenderer.setDisplayChartValues(true);
			// Adding a renderer for a slice
			defaultRenderer.addSeriesRenderer(seriesRenderer);
		}

		defaultRenderer.setChartTitle(" Gramme de Glucide par plat dans un repas");
		defaultRenderer.setChartTitleTextSize(30);
		defaultRenderer.setLegendTextSize(30);
		defaultRenderer.setLabelsColor(Color.BLACK);
		defaultRenderer.setLabelsTextSize(30);
		defaultRenderer.setClickEnabled(true);
		defaultRenderer.setSelectableBuffer(10);
		defaultRenderer.setShowLabels(false);
		defaultRenderer.setZoomButtonsVisible(false);

		final GraphicalView grfv = ChartFactory.getPieChartView(getBaseContext(), distributionSeries, defaultRenderer);
		
		return grfv;

	}

}
